'use strict';

/**
 * 模块定义
 */
angular.module('SURF', [
    'ngRoute',
    'pascalprecht.translate',
    'tm.pagination',
    'ng-constants',
    'ngFileUpload',
    'ngCookies'
]);


/**
 * 路由配置
 */
angular
    .module('SURF')
    .config(routeConfig);

function routeConfig($routeProvider,ROLES) {
    $routeProvider.when('/A01D01', {
        controller: 'A01D01Controller',
        service: 'A01D01Service',
        templateUrl: 'html/A01_Agent/A01D01.html',
        data: {
            roles: [ROLES.ADMIN, ROLES.AGENT],
            permissions: []
        },
        resolve: {
            initTranslate: function ($translate) {
                var lang = window.localStorage.lang || 'zh';
                return $translate.use(lang);
            }
        }
    }).when('/A01D02', {
        controller: 'A01D02Controller',
        service: 'A01D02Service',
        templateUrl: 'html/A01_Agent/A01D02.html',
        data: {
            roles: [ROLES.ADMIN, ROLES.AGENT],
            permissions: []
        }
    })
        .otherwise({redirectTo: '/A01D02'});
}


/**
 * 多语言配置
 */
angular
    .module('SURF')
    .config(translateConfig);

function translateConfig($translateProvider) {
    var lang = window.localStorage.lang || 'zh';
    if(isNull(lang)){
        lang = 'zh';
    }
    $translateProvider.preferredLanguage(lang);
    $translateProvider.useStaticFilesLoader({
        prefix: 'messages/messages_',
        suffix: '.json'
    });

}


angular
    .module('SURF').config(['$httpProvider', function ($httpProvider) {
    $httpProvider.interceptors.push(['$injector', function ($injector) {
        return $injector.get('AuthInterceptor');
    }
    ]);
}]);



/**
 * 路由控制
 */
angular
    .module('SURF')
    .run(routeChange);

function routeChange($rootScope, $location,CookieStoreService,COOKIE_STORE_KEYS,AuthService) {
    //路由控制
    $rootScope.$on('$routeChangeStart', function (event, next) {
        if ($location.path() == '/curve' || $location.path() == '/forgot'|| $location.path() == '/ResetPwd') {
            $rootScope.showCommonView = false;
        }else{
            $rootScope.showCommonView = true;
        }
        if (CookieStoreService.getValue(COOKIE_STORE_KEYS.USER_NAME) != null) {
            if (next.data != undefined) {
                var roles = next.data.roles;
                var permissions = next.data.permissions;
                if (!AuthService.isAllowed(roles, permissions)) {
                    event.preventDefault();
                }
            }
        } else {
            if($location.path() == '/forgot'){
                $location.path("/forgot");
            } else if($location.path() == '/ResetPwd'){
                $location.path("/ResetPwd");
            } else{
                $location.path($location.path());
            }
        }
    });
}

